package com.kgc.cart.controller;

import com.kgc.entity.TbItem;
import com.kgc.order.service.OrderService;
import com.kgc.utils.CookieUtils;
import com.kgc.utils.ItripResult;
import com.kgc.utils.JsonUtils;
import com.kgc.utils.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.List;

@Controller
public class OrderController {
@Autowired
private OrderService orderService;
    @RequestMapping("/order/order-cart")
    public String createOrder(HttpServletRequest request, Model model){
        List<TbItem> list=getCartList(request);
        model.addAttribute("cartList",list);
        return "order-cart";
    }

    private List<TbItem> getCartList(HttpServletRequest request){
        //购物车
        List<TbItem> list=null;
        //1.从cookie中得到一个购物车
        String cartCookie= CookieUtils.getCookieValue(request,"CART",true);
        //2.判断cookie是否有购物车
        if(!StringUtils.isEmpty(cartCookie)){
            list= JsonUtils.jsonToList(cartCookie,TbItem.class);
        }else{
            list=new ArrayList<>();
        }
        return list;
    }
    @RequestMapping("/order/create")
    public String createOrder(Order order, HttpServletRequest request, HttpServletResponse response){

        ItripResult result = orderService.createOrder(order);
        CookieUtils.setCookie(request,response,"CART",null,0);
        String id= result.getData().toString();//订单编号
        if(order.getPayType()==2){
            //weixing支付
            //order.getPayment() 总金额
            return "redirect:http://localhost:8087/wxpay/"+id+"/"+order.getPayment();
        }else if(order.getPayType()==3){
            //支付宝支付
            return "redirect:http://localhost:8087/aliPay/pay/"+id+"/"+order.getPayment();
        }else{
            //货到付款
            return "success";
        }

    }
}
